package TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        socket = new Socket(serverIP,serverPort);
    }
    public void start(){
        System.out.println("client start!");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNetwork = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true){
                //1、用户从控制台输入
                System.out.print("请输入-> ");
                String request = scanner.next();
                if(request.equals("exit")){
                    break;
                }
                //2、把用户输入的字符串发送给服务器
                printWriter.println(request);
                printWriter.flush();//冲刷缓冲区
                //3、从服务器读取响应
                if(!scannerNetwork.hasNext()){
                    break;
                }
                String response = scannerNetwork.next();
                //4、显示响应
                System.out.println(response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9090);
        tcpEchoClient.start();
    }
}
